﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.ComponentModel;



namespace Tenk.Controls
{
    /// <summary>
    /// Summary description for RequiredSelectedItemValidator
    /// </summary>
    public class RequiredSelectedItemValidator : BaseValidator
    { 

        private ListControl m_Ctrl;

        private int m_RequiredSelectedCount;

        /// <summary>
        /// Only valid when the control validator is list control
        /// </summary>
        [Browsable(true), DefaultValue(1),
            Description("Set must selected count when type is dropdownlist.")]
        public int RequiredSelectedCount
        {
            get { return m_RequiredSelectedCount; }
            set { m_RequiredSelectedCount = value; }
        }

        public RequiredSelectedItemValidator()
        {
            base.EnableClientScript = true;

            #region init private filed

            m_RequiredSelectedCount = 1;

            #endregion
        }

        protected override bool ControlPropertiesValid()
        {
            Control ctrl = this.FindControl(base.ControlToValidate);

             if (ctrl != null)
            {
                m_Ctrl = ctrl as ListControl;
                return (m_Ctrl != null);
            }
            else
                return false;  // raise exception
        }

        protected override bool EvaluateIsValid()
        {
            bool result = false;
            if (m_Ctrl is DropDownList)
            {
                result = m_Ctrl.SelectedIndex > 0;
            }
            else
            {
                int count = 0;

                foreach (ListItem item in m_Ctrl.Items)
                {
                    if (item.Selected) count++;
                }

                result = count > this.m_RequiredSelectedCount - 1;

            }
            return result;
        }

        protected override void OnPreRender(EventArgs e)
        {
            if (this.EnableClientScript) this.GenerateScript();
            base.OnPreRender(e);
        }

        protected virtual void GenerateScript()
        {
            StringBuilder script = new StringBuilder();

            script.Append("<script type=\"text/javascript\">\n");
            script.Append("//<![CDATA[\n");
            script.Append("     function " + this.ClientID + "_Validator() {\n");
            script.Append("         var isValid = false;\n");
            script.Append("         var id = document.getElementById(\"" + this.ClientID + "\").controltovalidate;\n");
            script.Append("         var el = document.getElementById(id);\n");

            if (this.FindControl(base.ControlToValidate) is DropDownList)
            {                
                script.Append("     isValid = el.selectedIndex > 0;\n");
            }
            else    //Other list type control
            {
                script.Append("     var chkList = el.getElementsByTagName(\"input\");\n");
                script.Append("     var count = 0;\n");
                script.Append("     for (var i=0; i<chkList.length; i++) {\n");
                script.Append("         if (chkList[i].type.toLowerCase() == \"checkbox\" || chkList[i].type.toLowerCase() == \"radio\") {\n");
                script.Append("             if (chkList[i].checked) count++; \n");
                script.Append("         }\n");
                script.Append("     }\n");
                script.Append("     if (count > " + (this.m_RequiredSelectedCount - 1).ToString() + ") {\n");
                script.Append("         isValid = true;\n");
                script.Append("     }\n");
            }
            
            script.Append("         return isValid;\n");
            script.Append("     }\n");
            script.Append("//]]>\n");
            script.Append("</script>\n");

            this.Page.ClientScript.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", this.ClientID + "_Validator");
            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), this.ClientID + "ListValidator", script.ToString(), false);
            
        }
    }
}
